<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegisterRequest;
use App\Http\Requests\UpdateProfileRequest;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\View\View;

class AuthController extends Controller
{
    /**
     * 处理用户登录
     */
    public function login(LoginRequest $request): JsonResponse
    {
        $credentials = $request->validated();

        // 尝试登录
        if (Auth::attempt([
            'email' => $credentials['email'],
            'password' => $credentials['password']
        ], $request->boolean('remember'))) {
            $request->session()->regenerate();

            /** @var User $user */
            $user = Auth::user();
            
            // 为插件生成API token
            $token = $user->createToken(
                'plugin-access',
                ['*'],
                now()->addDays(30) // 30天过期
            );

            return response()->json([
                'success' => true,
                'message' => '登录成功',
                'redirect' => route('dashboard'),
                'api_token' => $token->plainTextToken,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'email_verified_at' => $user->email_verified_at,
                ],
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => '邮箱或密码错误'
        ], 422);
    }

    /**
     * 处理用户注册
     */
    public function register(RegisterRequest $request): JsonResponse
    {
        try {
            $data = $request->validated();

            // 创建用户
            $user = User::create([
                'name' => $this->generateNameFromEmail($data['email']),
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
                'invite_code' => $data['invite_code'] ?? null,
            ]);

            // 触发注册事件
            event(new Registered($user));

            // 自动登录
            Auth::login($user);

            // 为插件生成API token
            $token = $user->createToken(
                'plugin-access',
                ['*'],
                now()->addDays(30) // 30天过期
            );

            return response()->json([
                'success' => true,
                'message' => '注册成功',
                'redirect' => route('dashboard'),
                'api_token' => $token->plainTextToken,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'email_verified_at' => $user->email_verified_at,
                ],
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '注册失败，请重试'
            ], 500);
        }
    }

    /**
     * 用户登出
     */
    public function logout(Request $request): RedirectResponse
    {
        /** @var User|null $user */
        $user = Auth::user();

        // 撤销所有插件访问令牌，防止浏览器插件在用户登出后继续使用旧令牌
        if ($user) {
            $user->tokens()->where('name', 'plugin-access')->delete();
        }

        // 注销 Web 会话
        Auth::logout();

        // 失效并重新生成 session 与 CSRF Token
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('auth')->with('message', '已成功登出');
    }

    /**
     * 显示忘记密码表单
     */
    public function showForgotPasswordForm(): View
    {
        return view('auth.forgot-password');
    }

    /**
     * 发送重置密码链接
     */
    public function sendResetLinkEmail(Request $request): JsonResponse
    {
        $request->validate(['email' => 'required|email']);

        $status = Password::sendResetLink(
            $request->only('email')
        );

        if ($status === Password::RESET_LINK_SENT) {
            return response()->json([
                'success' => true,
                'message' => '重置密码链接已发送到您的邮箱'
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => '发送失败，请检查邮箱地址'
        ], 422);
    }

    /**
     * 显示重置密码表单
     */
    public function showResetPasswordForm(string $token): View
    {
        return view('auth.reset-password', ['token' => $token]);
    }

    /**
     * 重置密码
     */
    public function resetPassword(Request $request): JsonResponse
    {
        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:8|confirmed',
        ]);

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user, $password) {
                $user->forceFill([
                    'password' => Hash::make($password)
                ])->setRememberToken(Str::random(60));

                $user->save();
            }
        );

        if ($status === Password::PASSWORD_RESET) {
            return response()->json([
                'success' => true,
                'message' => '密码重置成功',
                'redirect' => route('auth')
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => '密码重置失败，请重试'
        ], 422);
    }

    /**
     * 显示用户资料页面
     */
    public function profile(): View
    {
        return view('auth.profile', ['user' => Auth::user()]);
    }

    /**
     * 更新用户资料
     */
    public function updateProfile(UpdateProfileRequest $request): JsonResponse
    {
        /** @var User $user */
        $user = Auth::user();
        $data = $request->validated();

        // 如果要更新密码
        if (!empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $user->update($data);

        return response()->json([
            'success' => true,
            'message' => '资料更新成功'
        ]);
    }

    /**
     * 验证邮箱
     */
    public function verifyEmail(Request $request): RedirectResponse
    {
        $user = User::find($request->route('id'));

        if (!$user) {
            return redirect()->route('auth')->with('error', '用户不存在');
        }

        if ($user->hasVerifiedEmail()) {
            return redirect()->route('dashboard')->with('message', '邮箱已验证');
        }

        if ($user->markEmailAsVerified()) {
            event(new Verified($user));
        }

        return redirect()->route('dashboard')->with('message', '邮箱验证成功');
    }

    /**
     * 发送邮箱验证链接
     */
    public function sendVerificationEmail(Request $request): JsonResponse
    {
        $user = $request->user();

        if ($user->hasVerifiedEmail()) {
            return response()->json([
                'success' => false,
                'message' => '邮箱已验证'
            ]);
        }

        $user->sendEmailVerificationNotification();

        return response()->json([
            'success' => true,
            'message' => '验证邮件已发送'
        ]);
    }

    /**
     * 获取用户API token（用于插件同步）
     */
    public function getApiToken(Request $request): JsonResponse
    {
        /** @var User $user */
        $user = $request->user();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => '用户未登录'
            ], 401);
        }

        // 撤销旧的plugin-access token
        $user->tokens()->where('name', 'plugin-access')->delete();

        // 创建新的token
        $token = $user->createToken(
            'plugin-access',
            ['*'],
            now()->addDays(30) // 30天过期
        );

        // 记录token刷新时间（用于状态同步判断）
        $request->session()->put('last_token_refresh', time());

        return response()->json([
            'success' => true,
            'message' => 'API token 获取成功',
            'api_token' => $token->plainTextToken,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'email_verified_at' => $user->email_verified_at,
            ],
            'expires_at' => $token->accessToken->expires_at,
            'refresh_time' => now()->timestamp
        ]);
    }

    /**
     * 撤销API token
     */
    public function revokeApiToken(Request $request): JsonResponse
    {
        /** @var User $user */
        $user = $request->user();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => '用户未登录'
            ], 401);
        }

        // 撤销所有plugin-access token
        $deletedCount = $user->tokens()->where('name', 'plugin-access')->delete();

        return response()->json([
            'success' => true,
            'message' => "已撤销 {$deletedCount} 个插件访问令牌"
        ]);
    }

    /**
     * 从邮箱生成用户名
     */
    private function generateNameFromEmail(string $email): string
    {
        $name = explode('@', $email)[0];
        
        // 如果用户名已存在，添加随机数字
        $originalName = $name;
        $counter = 1;
        
        while (User::where('name', $name)->exists()) {
            $name = $originalName . $counter;
            $counter++;
        }
        
        return $name;
    }
} 